<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\BaseController;
use app\common\model\Region;
use app\common\model\User\User as UserMOdel;
use app\home\middleware\Auth;
use think\facade\View;
use app\common\model\Post\Post as PostModel;
use app\common\model\Post\Comment as CommentModel;
use app\common\model\User\Record as RecordModel;

class User extends BaseController
{
    // 控制器中间件
    protected $middleware = [
        Auth::class
    ];

    protected function initialize()
    {
        parent::initialize();

        $this->UserModel = new UserMOdel();

        $this->RegionModel = new Region();
    }

    public function index()
    {
        $userid = $this->request->param('userid',0);

        // 如果该参数存在，那么说查看其他用户
        if($userid)
        {
            // 查询该用户是否存在
            $User = $this->UserModel->find($userid);

            // 如果不存在
            if(!$User)
            {
                $this->error('要查看的用户不存在，请重新选择');
                
            }
        }

        // 如果有接收用户id拿查询的数据给视图，否则把登录的数据给视图
        $User = $userid ? $User : $this->request->LoginUser;

        $PostList = PostModel::withJoin(['user','cate'])->where(['userid' => $User['id']])->order('post.createtime','desc')->paginate(['list_rows' => 10,'query' => request()->param()]);
        
        $CommentList = CommentModel::withJoin(['user','post'])->where(['comment.userid' => $User['id']])->order('comment.createtime','desc')->paginate(['list_rows' => 10,'query' => request()->param(),'var_page' => 'pages']);
        

        return View::fetch('',[
            'User' => $User,
            'PostList' => $PostList,
            'CommentList' => $CommentList
        ]);

        
    }

    // 个人资料
    public function profile()
    {
        $title = '个人资料';

        if($this->request->isPost())
        {
            $action = $this->request->param('action','');

            if($action === 'profile')
            {
                // 接收所有的参数
                $params = $this->request->param();
                
                // 封装更新数据
                $UserData = [
                    'nickname' => $params['nickname'],
                    'sex' => $params['sex'],
                    'province' => $params['province'],
                    'city' => $params['city'],
                    'district' => $params['district'],
                    'content' => $params['content']
                ];

                // 助手函数实例化验证器
                $vaildate = validate('app\common\validate\User\User.profile');

                // 判断是否验证失败
                if(!$vaildate->check($UserData))
                {
                    $this->error($vaildate->getError());
                    
                }

                // 更新数据
                // $result = $this->UserModel->where(['id' => $this->request->LoginUser['id']])->save($UserData);
                $User = $this->UserModel->find($this->request->LoginUser['id']);

                $result = $User->save($UserData);

                if($result === FALSE)
                {
                    $this->error('更新个人资料失败');
                    
                }else{
                    $this->success('更新个人资料成功');
                    
                }
            }

            if($action === 'avatar')
            {
                // 组装一个空的数组
                $AvatarData = [];

                // 调用图片上传的函数
                $avatar = upload('avatar');


                // 如果上传失败，则提示
                if($avatar['code'] === 0)
                {
                    $this->error($avatar['msg']);
                    
                }else {
                    // 上传成功后获取返回的图片名称追加到数组里
                    $AvatarData['avatar'] = '/' . $avatar['data'];
                }

                // 更新到数据库
                $User = $this->UserModel->find($this->request->LoginUser['id']);

                $result = $User->save($AvatarData);

                if($result)
                {
                    @is_file('.' . $this->request->LoginUser['avatar']) && @unlink('.' . $this->request->LoginUser['avatar']);
                    $this->error('更新头像成功');
                    
                }else{
                    @is_file('.' . $AvatarData['avatar']) && @unlink('.' . $AvatarData['avatar']);
                    $this->error('更新头像失败');
                    
                }

                
            }

            if($action === 'password')
            {
                // 当前密码
                $NowPass = $this->request->param('nowpass','');

                // 新密码
                $pass = $this->request->param('pass','');

                // 确认密码
                $repass =$this->request->param('repass','');

                // 前台已经做不能为空的逻辑，这里只需要做新密码与确认密码是否一致
                if($pass != $repass)
                {
                    $this->error('新密码与确认密码不一致，请重新输入');
                    
                }

                // 判断输入的密码与数据库的密码匹配是否正确，先加密一下旧密码
                $OldPass = md5($NowPass . $this->request->LoginUser['salt']);

                // 判断
                if($OldPass != $this->request->LoginUser['password'])
                {
                    $this->error('密码错误，请重新输入');
                    
                }

                // 生成密码盐
                $salt = build_ranstr();

                // 加密
                $newPass = md5($pass . $salt);

                // 封装更新的数据
                $UserData = [
                    'password' => $newPass,
                    'salt' => $salt
                ];

                $User = $this->UserModel->find($this->request->LoginUser['id']);

                // 更新
                $result = $User->save($UserData);


                if($result)
                {
                    // 更新成功，需要重新登录
                    cookie('LoginUser',null);
                    $this->success('更新密码成功，请重新登录','/home/index/login');
                    
                }else{
                    $this->error('更新密码失败');
                    
                }
            }

            if($action === 'cover')
            {
                // 组装一个空的数组
                $CoverData = [];

                // 调用图片上传的函数
                $cover = upload('cover');


                // 如果上传失败，则提示
                if($cover['code'] === 0)
                {
                    $this->error($cover['msg']);
                    
                }else {
                    // 上传成功后获取返回的图片名称追加到数组里
                    $CoverData['cover'] = '/' . $cover['data'];
                }

                // 更新到数据库
                $User = $this->UserModel->find($this->request->LoginUser['id']);

                $result = $User->save($CoverData);

                if($result)
                {
                    @is_file('.' . $this->request->LoginUser['cover']) && @unlink('.' . $this->request->LoginUser['cover']);
                    $this->error('更新封面图成功');
                    
                }else{
                    @is_file('.' . $CoverData['cover']) && @unlink('.' . $CoverData['cover']);
                    $this->error('更新封面图失败');
                    
                }

                
            }
        }


        // 查询省份的数据
        $provinces = $this->RegionModel->where(['grade' => 1])->select();

        // 判断登录用户的省份是否为空
        if(empty($this->request->LoginUser['province']))
        {
            $citys = [];
        }else {
            $citys = $this->RegionModel->where(['parentid' => $this->request->LoginUser['province']])->select();
        }

        if(empty($this->request->LoginUser['city']))
        {
            $districts = [];
        }else {
            $districts = $this->RegionModel->where(['parentid' => $this->request->LoginUser['city']])->select();
        }

        // 赋值给视图
        return View::fetch('',[
            'title' => $title,
            'provinces' => $provinces,
            'citys' => $citys,
            'districts' => $districts
        ]);
    }

    // 发送邮件
    public function email()
    {
        if($this->request->isAjax())
        {
            // 安装指令 => composer require phpmailer/phpmailer 安装PHP发送邮件的依赖包

            // 获取认证的邮箱
            $email = $this->request->LoginUser['email'];

            // 密码盐
            $salt = $this->request->LoginUser['salt'];

            // 进行加密 邮箱+密码盐
            $EmailSalt = md5($email . $salt);

            // 内容
            $msg = "<a href='http://www.tp6.ask.com/home/index/email?auth=$EmailSalt'>请点击认证</a>";

            $result = EmailSend($this->request->LoginUser['nickname'],$this->request->LoginUser['email'],$msg);

            if($result === FALSE)
            {
                $this->error('邮件发送失败');
            }else{
                $this->success('邮件发送成功');
            }
        }
    }

    // 消费记录
    public function record()
    {
        $title = '我的消费记录';

        $RecordList = RecordModel::withJoin(['user'])->where(['userid' => $this->request->LoginUser['id']])->order('record.createtime','desc')->paginate(['list_rows' => 10,'query' => request()->param()]);

        $total = $RecordList->total();


        return View::fetch('',[
            'title' => $title,
            'total' => $total,
            'RecordList' => $RecordList
        ]);
    }

    // 我的帖子
    public function post()
    {
        $title = '我的帖子';

        $PostList = PostModel::withJoin(['user'])->where(['userid' => $this->request->LoginUser['id']])->order('post.createtime','desc')->paginate(['list_rows' => 10,'query' => request()->param()]);

        $total = $PostList->total();


        return View::fetch('',[
            'title' => $title,
            'total' => $total,
            'PostList' => $PostList
        ]);
    }

    // 查询所选地区码的异步请求
    public function region()
    {
        // 是否是ajax
        if($this->request->isAjax())
        {
            // 接收所选的地区码
            $code = $this->request->param('code','');

            // 判断为空
            if(empty($code))
            {
                $this->error('获取地区码失败');
                
            }

            // 查询
            $region = $this->RegionModel->where(['parentid' => $code])->field('code,name')->select();
            
            // 返回结果
            if($region)
            {
                $this->success('查询成功',null,$region);
                
            }else{
                $this->error('查询失败');
                
            }
        }
    }
}
